package com.example.httpurlconnection_get_post419;

        import android.os.Handler;
        import android.os.Message;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.View;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TextView;
        import android.widget.Toast;

        import com.android.volley.RequestQueue;
        import com.android.volley.Response;
        import com.android.volley.VolleyError;
        import com.android.volley.toolbox.StringRequest;
        import com.android.volley.toolbox.Volley;

        import java.io.BufferedReader;
        import java.io.DataOutputStream;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.net.HttpURLConnection;
        import java.net.MalformedURLException;
        import java.net.URL;
        import java.util.regex.Matcher;
        import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
    private static final int GET_DATA_SUCCESS = 1001 ;
    private final String baseUrl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
    private EditText edtPhone;
    private Button btnQuery;
    private TextView tvResult;
    private Handler handler;
    private RequestQueue requestQueue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        requestQueue = Volley.newRequestQueue(MainActivity.this);

        initHandler();
        edtPhone = findViewById(R.id.edt_phone);
        btnQuery = findViewById(R.id.btn_query);
        tvResult = findViewById(R.id.tv_result);

        btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               /* String url = "http://www.baidu.com";
                StringRequest stringRequest = new StringRequest(
                        url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String s) {
                                Log.e("onResponse", s);
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                });
                requestQueue.add( stringRequest );*/
                queryWithHttpUrlConnectionPost(edtPhone.getText().toString());


//                String phone = edtPhone.getText().toString();
                // 判断是不是电话号码  如果不是
                // 给一个Toast 然后return
//                if (!isValid(phone)) {
//                    Toast.makeText(MainActivity.this, "您输入的号码有误，请重新输入", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                queryWithHttpUrlConnectionGet(phone);
//                queryWithHttpUrlConnectionPost(phone);
            }
        });
    }

    private void queryWithHttpUrlConnectionPost(final String phone) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String baseUrl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
                    URL url = new URL(baseUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    // 要将参数通过post方式传递
                    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
                    outputStream.writeBytes("mobileCode="+phone+"&userID=");
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuffer buffer =new StringBuffer();
                    String line = reader.readLine();
                    while(line != null){
                        buffer.append(line);
                        line = reader.readLine();
                    }

                    Message message = new Message();
                    message.what = GET_DATA_SUCCESS;
                    message.obj = buffer.toString();
                    handler.sendMessage(message);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    private void initHandler() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if(message.what == GET_DATA_SUCCESS){
                    String result = (String) message.obj;
                    tvResult.setText(result);
                    return true;
                }
                return false;
            }
        });
    }

    // 判断号码是否有效
    private boolean isValid(String phone) {
        String regex = "^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7,9]))\\d{8}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    private void queryWithHttpUrlConnectionGet(final String phone) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String urlstr = baseUrl + "?mobileCode=" + phone + "&userID=";
                try {
                    URL url = new URL(urlstr);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuffer buffer =new StringBuffer();
                    String line = reader.readLine();
                    while(line != null){
                        buffer.append(line);
                        line = reader.readLine();
                    }

                    Message message = new Message();
                    message.what = GET_DATA_SUCCESS;
                    message.obj = buffer.toString();
                    handler.sendMessage(message);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }
}
